<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace controller;

/**
 * Description of ShopAdmin_Products
 *
 * @author Damian
 */
class ShopAdmin_Products extends Seller {

    public $productList = null;
    public function index() {
        $page = (\library\RequestMethods::get("Page")) ? \library\RequestMethods::get("Page") : 1;
        if (!is_numeric($page)) {
            $page = 1;
        }
        $allPages = new \model\Criteria();
        $all = $allPages->from(\model\TblProduct::getModel()->getTable())->count();
        $pagesCount = ceil($all / $this->perPage);
        $pages = new \view\Pagination($page, 1, $pagesCount, "./" . $this->shop->URL . "/" . "ShopAdmin_Products");
        $session = \library\Registry::get("session");
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "lista Twoich produktów");
        $layoutView->set("pages", $pages);
        $productsCriteria = new \model\Criteria();
        $view = $this->getActionView();
        $productsCriteria->from(\model\TblProduct::getModel()->getTable())
                ->join(\model\TblManufacturer::getModel())
                ->join(\model\TblCategory::getModel())
                ->join(\model\TblCurrency::getModel())
                ->limit($this->perPage, $page)
                ->where(\model\TblProduct::SHOP_ID, "=", $this->shop->ShopID, \model\TblProduct::getModel()->getTable());
        if (\library\RequestMethods::get("order")){
            $session->set("orderProducts",\library\RequestMethods::get("order"));
            }
        $view->set("order",$session->get("orderProducts"));
        $order = \model\TblProduct::createOrderString($session->get("orderProducts"));
        $productsCriteria->order($order[0], $order[1],  \model\TblProduct::getModel()->getTable());
        $products = \model\TblProduct::getModel()->all($productsCriteria);
        $productsData = new \model\DataTable($products, false);
        $this->productList = $productsData->getModelData();
       // var_dump($this->productList);
        foreach ($this->productList as &$product) {
            $defaultPictureCriteria = new \model\Criteria();
            $product["DefaultPicture"] = $defaultPictureCriteria->from(\model\TblProductPicture::getModel()->getTable())
                            ->where(\model\TblProductPicture::PRODUCT_ID, "=", $product["ProductID"])
                            ->where(\model\TblProductPicture::DEFAULT_PICTURE, "=", "1", false, " and ")->count();
        }
        $session->set("productList", $this->productList);
        
        $view->set("products", $this->productList);
        $this->render();
    }

    public function add() {
        $date = new \DateTime();
        $session = \library\Registry::get("session");
        $view = $this->getActionView();
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Dodajesz nowy produkt");
        $view->set("shopname", $this->shop->Name);
        if (sizeof($_POST) > 0) {
            $pictures = \library\RequestMethods::post("pictures", null, false);
            $features = \library\RequestMethods::post("features", null, false);
            $related = \library\RequestMethods::post("related", null, false);
            $mainPicture = \library\RequestMethods::post("mainPicture");
            $product = new \model\TblProduct([
                \model\TblProduct::SHOP_ID => $this->shop->ShopID,
                \model\TblProduct::NAME => \library\RequestMethods::post("name"),
                \model\TblProduct::SHORT_DESCRIPTION => \library\RequestMethods::post("shortDesription"),
                \model\TblProduct::DESCRIPTION => \library\RequestMethods::post("fullDescritpion"),
                \model\TblProduct::MANUFACTURER_ID => \library\RequestMethods::post("manufacturer"),
                \model\TblProduct::CATEGORY_ID => \library\RequestMethods::post("category"),
                \model\TblProduct::VAT => \library\RequestMethods::post("vat"),
                \model\TblProduct::GROSS_PRICE => \library\RequestMethods::post("gross"),
                \model\TblProduct::NET_PRICE => \library\RequestMethods::post("net"),
                \model\TblProduct::ACTIVE => (strcmp(\library\RequestMethods::post("active"), "on") == 0) ? 1 : 0,
                \model\TblProduct::AMOUNT => \library\RequestMethods::post("amount"),
                \model\TblProduct::CURRENCY_ID => 1,
                \model\TblProduct::VISABLE => 1,
                \model\TblProduct::AVG_MARK=>-1,
                \model\TblProduct::ADDITION_DATE =>$date->format('Y-m-d H:i:s')
            ]);
            if ($product->validate()) {
                try {
                    $session->erase("productList");
                    $product->ProductID = $product->save();
                    $product->setRelatedPictures($pictures, $mainPicture);
                    $product->setRelations($features, $related);
                    $view = $this->getActionView();
                    $view->set("success", "Pomyślnie dodano produkt");
                    // $this->render();
                    //return;
                } catch (\model\exceptions\ExceptionSQLQUery $ex) {
                    if ($ex->getCode() == 1062) {
                        $errors = array();
                        $errors["Name"][] = "Produkt o takiej nazwie już istnieje";
                        $view = $this->getActionView();
                        $view->set("errors", $errors);
                    } else {
                        throw $ex;
                    }
                }
            }
            else {
                var_dump($product->getErrors());
                die();
            }
        } else {
            
            $manufacturers = \model\TblManufacturer::getModel()->getAllByShopID($this->shop->ShopID);
            $manufacturersData = new \model\DataTable($manufacturers);
            $manufacturersModelData = $manufacturersData->getModelData(true);
            $categories = \model\TblCategory::getModel()->getAllByShopID($this->shop->ShopID,FALSE);
            $categoriesData = new \model\DataTable($categories);
            $categoriesModelData = $categoriesData->getModelData(true);
            $picturesCriteria = new \model\Criteria();
            $picturesCriteria->from(\model\TblPicture::getModel()->getTable())->where(\model\TblPicture::SHOP_ID, "=", $this->shop->ShopID);
            $pictures = \model\TblPicture::getModel()->all($picturesCriteria);
            $picturesData = new \model\DataTable($pictures);
            $picturesModelData = $picturesData->getModelData(true);
            $view->set("manufacturers", $manufacturersModelData);
            $view->set("categories", $categoriesModelData);
            $view->set("pictures", $picturesModelData);
            $this->render();
        }
    }

    public function edit() {
        $session = \library\Registry::get("session");
        $productID = \library\RequestMethods::get("ProductID");
        if (!$productID) {
            $this->redirect($this->shop->URL . "/ShopAdmin_Products");
        }
        $productCriteria = new \model\Criteria();
        $productCriteria->from(\model\TblProduct::getModel()->getTable())
                ->where(\model\TblProduct::SHOP_ID, "=", $this->shop->ShopID, \model\TblProduct::getModel()->getTable())
                ->where(\model\TblProduct::ID,"=", $productID,  \model\TblProduct::getModel()->getTable()," and ")
                ->join(\model\TblProductPicture::getModel())
                ->join(\model\TblPicture::getModel())
                ->join(\model\TblManufacturer::getModel())
                ->join(\model\TblCategory::getModel())
                ->join(\model\TblCurrency::getModel());
        //var_dump($productCriteria->getSelectQuery());
        $product = \model\TblProduct::getModel()->first($productCriteria)->ProductID;
       // var_dump($product);
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Edytujesz produkt " . $product->Name);
        if (!$product) {
            $this->redirect($this->shop->Name . "/ShopAdmin_Products");
        }
        /* @var $product \model\TblProduct */
        $view = $this->getActionView();
        $view->set("shopname", $this->shop->Name);
        if (sizeof($_POST) > 0) {
            $pictures = \library\RequestMethods::post("pictures", null, false);
            $features = \library\RequestMethods::post("features", null, false);
            $related = \library\RequestMethods::post("related", null, false);
            $mainPicture = \library\RequestMethods::post("mainPicture");
            $product->clearRelations();
            $product->ShopID = $this->shop->ShopID;
            $product->Name = \library\RequestMethods::post("name");
            $product->Active = (strcmp(\library\RequestMethods::post("active"), "on") == 0) ? 1 : 0;
            $product->ShortDescription = \library\RequestMethods::post("shortDesription");
            $product->Description = \library\RequestMethods::post("fullDescritpion");
            $product->ManufacturerID = \library\RequestMethods::post("manufacturer");
            $product->CategoryID = \library\RequestMethods::post("category");
            $product->VAT = intval(\library\RequestMethods::post("vat"));
            $product->GrossPrice = floatval(\library\RequestMethods::post("gross"));
            $product->NetPrice = floatval(\library\RequestMethods::post("net"));
            $product->Visable = true;
            $product->Amount = intval(\library\RequestMethods::post("amount"));
            $product->CurrencyID = 1;
            if ($product->validate()) {
                $session->erase("productList");
                $product->save();
               $product->setRelatedPictures($pictures, $mainPicture);
                $product->setRelations($features, $related);
                $view = $this->getActionView();
                $view->set("success", "Pomyślnie zapisano zmiany");
            }
        } else {
            //producenci
            $manufacturers = \model\TblManufacturer::getModel()->getAllByShopID($this->shop->ShopID);
            $manufacturersData = new \model\DataTable($manufacturers);
            $manufacturersModelData = $manufacturersData->getModelData(true);
            //kategorie
            $categories = \model\TblCategory::getModel()->getAllByShopID($this->shop->ShopID,false);
            $categoriesData = new \model\DataTable($categories);
            $categoriesModelData = $categoriesData->getModelData(true);
            //cechy z kategorii
            $featuresDatatable = new \model\DataTable(\model\TblCategoryFeature::getModel()->getAllByCategory($product->CategoryID));
            $featuresData = $featuresDatatable->getModelData(true);
            
            foreach ($featuresData as &$feature){
                $ValuesCriteria = new \model\Criteria();
                $ValuesCriteria->from(\model\TblFeatureValue::getModel()->getTable())
                        ->where(\model\TblFeatureValue::CATEGORY_FEATURE_ID, "=", $feature->CategoryFeatureID);
                    $values = new \model\DataTable(\model\TblFeatureValue::getModel()->all($ValuesCriteria));
                    $feature->values=$values->getModelData(true);                
            }
            //cechy produktów
            $productsFeaturesCriteria = new \model\Criteria();
            $productsFeaturesCriteria->from(\model\TblProductFeature::getModel()->getTable())
                    ->join(\model\TblFeatureValue::getModel())
                    ->where(\model\TblProductFeature::PRODUCT_ID, "=", $product->ProductID);
            $productsFeaturesDataTable = new \model\DataTable(\model\TblCategoryFeature::getModel()->all($productsFeaturesCriteria), true, "CategoryFeatureID");
            //var_dump(new \model\DataTable(\model\TblCategoryFeature::getModel()->all($productsFeaturesCriteria), true, "CategoryFeatureID"));
            //powiązane produkty
            $relatedProdutcs = \model\TblRelatedProduct::findRelatedProducts($product->ProductID, $this->shop->ShopID);
            if ($relatedProdutcs) {
                $view->set("relatedProducts", $relatedProdutcs->getModelData(true));
            }
            //obrazki
            $picturesCriteria = new \model\Criteria();
            $picturesCriteria->from(\model\TblPicture::getModel()->getTable())->where(\model\TblPicture::SHOP_ID, "=", $this->shop->ShopID);
            $pictures = \model\TblPicture::getModel()->all($picturesCriteria);
            $picturesData = new \model\DataTable($pictures);
            $picturesModelData = $picturesData->getModelData(true);
            $ProductPictureCriteria = new \model\Criteria();
            $ProductPictureCriteria->from(\model\TblProductPicture::getModel()->getTable());
           $ProductPictureCriteria->where(\model\TblProductPicture::PRODUCT_ID, "=", $productID, \model\TblProductPicture::getModel()->getTable());
            $productPicture = \model\TblProductPicture::getModel()->all($ProductPictureCriteria);
            $productCriteriaData = new \model\DataTable($productPicture, true, "PictureID");
            $currencyCriteria = new \model\Criteria();
            $currencyCriteria->from(\model\TblCurrency::getModel()->getTable());
            $currency = \model\TblCurrency::getModel()->all($currencyCriteria);
            $currencyData = new \model\DataTable($currency);
            $currencyModelData = $currencyData->getModelData(true);
            $view->set("categoryFeatures", $featuresData);
            $view->set("productFeatures", $productsFeaturesDataTable->getModelData(true));
            $view->set("manufacturers", $manufacturersModelData);
            $view->set("productPictures", $productCriteriaData->getModelData());
            $view->set("categories", $categoriesModelData);
            $view->set("pictures", $picturesModelData);
            $view->set("currency", $currencyModelData);
            $view->set("product", $product);
            $this->render();
        }
    }

    public function fastEdit() {
        $page = (\library\RequestMethods::get("Page")) ? \library\RequestMethods::get("Page") : 1;
        if (!is_numeric($page)) {
            $page = 1;
        }
        if (sizeof($_POST) > 0) {
            $categoryID = \library\RequestMethods::post("category");
            $product = \model\TblProduct::getModel()->getByPrimaryKey(intval(\library\RequestMethods::post("id")));
            /* @var $product \model\TblProduct  */
            if ($product && $product->CategoryID != $categoryID) {
                $deleteFeatures = new \model\Criteria();
                $deleteFeatures->from(\model\TblProductFeature::getModel()->getTable())
                        ->where(\model\TblProductFeature::PRODUCT_ID, "=", $product->ProductID);
                $deleteFeatures->delete();
            }
            $product->Name = \library\RequestMethods::post("name");
            $product->ManufacturerID = \library\RequestMethods::post("manufacturer");
            $product->CategoryID = \library\RequestMethods::post("category");
            $product->VAT = intval(\library\RequestMethods::post("vat"));
            $product->Amount = intval(\library\RequestMethods::post("amount"));
            $product->Active = intval(\library\RequestMethods::post("active"));
            $product->GrossPrice = floatval(\library\RequestMethods::post("price"));
            $product->NetPrice = $product->GrossPrice/(1+$product->VAT/100);
            $product->CurrencyID = 1;
            if ($product->validate()) {
                $product->save();
            }
            return;
        }
        $allPages = new \model\Criteria();
        $all = $allPages->from(\model\TblProduct::getModel()->getTable())->count();
        $pagesCount = ceil($all / $this->perPage);
        $pages = new \view\Pagination($page, 1, $pagesCount, "./" . $this->shop->URL . "/" . "ShopAdmin_Products/fastedit");
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "lista Twoich produktów");
        $layoutView->set("pages", $pages);
        $view = $this->getActionView();
        $session = \library\Registry::get("session");
        $productsCriteria=  \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        if (\library\RequestMethods::get("order")){
            $session->set("orderProducts",\library\RequestMethods::get("order"));
            }
        $view->set("order",$session->get("orderProducts"));
        $order = \model\TblProduct::createOrderString($session->get("orderProducts"));
        $productsCriteria->order($order[0], $order[1],  \model\TblProduct::getModel()->getTable());
        $products = \model\TblProduct::getModel()->all($productsCriteria);
        $productsData = new \model\DataTable($products, false);
        $this->productList = $productsData->getModelData();
        //producenci
        $manufacturers = \model\TblManufacturer::getModel()->getAllByShopID($this->shop->ShopID);
        $manufacturersData = new \model\DataTable($manufacturers);
        $manufacturersModelData = $manufacturersData->getModelData(true);
        //kategorie
        $categories = \model\TblCategory::getModel()->getAllByShopID($this->shop->ShopID);
        $categoriesData = new \model\DataTable($categories);
        $categoriesModelData = $categoriesData->getModelData(true);
        
        $view->set("categories", $categoriesModelData);
        $view->set("manufacturers", $manufacturersModelData);
        $view->set("categories", $categoriesModelData);
        $view->set("products", $this->productList);
        $this->render();
    }

}
